# 文件路径
$inputFile = ".\in"
$outputDir = ".\output"  # 输出文件夹

# 创建输出目录
if (!(Test-Path $outputDir)) {
    New-Item -ItemType Directory -Path $outputDir
}

# 百度翻译 API 配置
$baiduAppId = "20230720001750945"  # 替换为你的百度翻译 APP ID
$baiduSecretKey = "Hz3w05zL07HGEBbE3SQP"  # 替换为你的百度翻译 Secret Key

# 函数：生成百度翻译签名
function Generate-BaiduSign {
    param (
        [string]$AppId,
        [string]$Query,
        [int]$Salt,
        [string]$SecretKey
    )
    # 签名公式：MD5(appid + q + salt + secret_key)
    $rawString = "$AppId$Query$Salt$SecretKey"
    $md5 = [System.Security.Cryptography.MD5]::Create()
    $bytes = [System.Text.Encoding]::UTF8.GetBytes($rawString)
    $hashBytes = $md5.ComputeHash($bytes)
    -join ($hashBytes | ForEach-Object { "{0:x2}" -f $_ })
}

# 函数：百度翻译
function Translate-TextWithBaidu {
    param (
        [string]$Text,
        [string]$TargetLanguage = "zh"
    )

    # 修复 Salt 值问题
    $salt = Get-Random -Minimum 100000000 -Maximum 999999999  # 确保在 Int32 范围内
    $sign = Generate-BaiduSign -AppId $baiduAppId -Query $Text -Salt $salt -SecretKey $baiduSecretKey

    # 百度翻译 API 地址
    $endpoint = "http://api.fanyi.baidu.com/api/trans/vip/translate"
    $params = @{
        q = $Text
        from = "auto"  # 自动检测源语言
        to = $TargetLanguage
        appid = $baiduAppId
        salt = $salt
        sign = $sign
    }

    try {
        $response = Invoke-RestMethod -Uri $endpoint -Method Post -Body $params
        if ($response.trans_result -ne $null) {
            return $response.trans_result[0].dst
        } else {
            Write-Host "百度翻译 API 未返回有效结果：$($response)"
            return $null
        }
    } catch {
        Write-Host "百度翻译请求失败：$($_.Exception.Message)"
        return $null
    }
}

# 函数：从 Codeforces API 获取题目信息
function Get-Problem-Details {
    param (
        [string]$Url
    )

    if ($Url -match "https://codeforces\.com/problemset/problem/(\d+)/([A-Z]+)") {
        $contestId = $Matches[1]
        $index = $Matches[2]
        $apiUrl = "https://codeforces.com/api/problemset.problems"

        $response = Invoke-RestMethod -Uri $apiUrl -Method Get

        $problem = $response.result.problems | Where-Object { $_.contestId -eq $contestId -and $_.index -eq $index }
        if ($problem) {
            return @{
                name = $problem.name
                link = $Url
                difficulty = $problem.rating
                contestId = $contestId
                index = $index
            }
        } else {
            Write-Host "无法找到题目：$Url"
            return $null
        }
    } else {
        Write-Host "无效的链接格式：$Url"
        return $null
    }
}

# 主逻辑
$urls = Get-Content $inputFile
foreach ($url in $urls) {
    $problemDetails = Get-Problem-Details -Url $url

    if ($problemDetails -ne $null) {
        # 使用百度翻译将题目名称翻译成中文
        $translatedTitle = Translate-TextWithBaidu -Text $problemDetails.name

        if ($translatedTitle -eq $null) {
            Write-Host "翻译失败，使用英文标题：$($problemDetails.name)"
            $translatedTitle = $problemDetails.name
        } else {
            Write-Host "翻译成功：$translatedTitle"
        }

        # 使用题目编号作为文件名，确保文件名合法
        $fileName = "$($problemDetails.contestId)_$($problemDetails.index).md" -replace "[^\w]", "."
        $filePath = Join-Path $outputDir $fileName

        # 构建 Markdown 内容
        $markdownContent = @"
---
title: $translatedTitle
date: $(Get-Date -Format "yyyy-MM-dd")
contestId: $($problemDetails.contestId)
index: $($problemDetails.index)
name: $($problemDetails.name)
Difficulty: $($problemDetails.difficulty)
---

## [$translatedTitle]($($problemDetails.link))

## Examples

### Title provided

### TEST

## Note

## Parsing

## Core code

```c++

```
"@

        # 写入文件
        Set-Content -Path $filePath -Value $markdownContent -Encoding UTF8
        Write-Host "已保存题目到文件：$filePath"
    }
}